package com.hnucm.springboot.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class MySercurityConfig extends WebSecurityConfigurerAdapter {
   @Autowired
    MyUserService myUserService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(myUserService).passwordEncoder(new BCryptPasswordEncoder());
//        auth.inMemoryAuthentication()
//                .withUser("user")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .authorities("user")
//                .and()
//                .withUser("admin")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .authorities("user","admin");
    }
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.authorizeHttpRequests()
                .antMatchers("/home","/test","/personlist","/login","/**").permitAll()
                .antMatchers("/user").hasAuthority("user")
                .antMatchers("/admin").hasAuthority("admin")
                .anyRequest().authenticated();
        http.formLogin()
                .loginPage("/login")   //默认需要权限
                .loginProcessingUrl("/user/login")
                .and()
                .logout()
                .logoutUrl("/logout");
        http.cors();
        http.csrf().disable();
    }
}
